
import useSWR from 'swr';
import { processData } from '../utils/processData';

const API_ENDPOINTS = {
  topGrossing: (limit: number) => 
    `https://itunes.apple.com/hk/rss/topgrossingapplications/limit=${limit}/json`,
  topFree: (limit: number) =>
    `https://itunes.apple.com/hk/rss/topfreeapplications/limit=${limit}/json`,
  appsDetail: (id: string) =>  `https://itunes.apple.com/hk/lookup?id=${id}`
};

type Item = {
    id: { attributes: { 'im:id': string } };
}


const fetcher = (url: string) => fetch(url).then(res => {
    return res.json();
}).then(res => {
    let id = ''
    res.feed.entry.forEach((item: Item) => {
        const $id = item.id.attributes['im:id'];
        id += $id ? $id + ',': '';
    })
    return fetch(API_ENDPOINTS.appsDetail(id));
}).then(res => {
    return res.json();
})

export const useAppData = () => {
  // 获取基础数据
  const { data: topGrossing } = useSWR(API_ENDPOINTS.topGrossing(10), fetcher);
  const { data: topFree } = useSWR(API_ENDPOINTS.topFree(100), fetcher);
  
  // 处理数据
  return {
    recommended: processData(topGrossing?.results || []),
    freeApps: processData(topFree?.results || [])
  };
};